//index.js
//获取应用实例
const app = getApp()

Page({
  globalData: {
    appid: 'wx7879ea0d2718b12a', //appid需自己提供，此处的appid我随机编写
    secret: 'bfd933c7d70e5ecbdaa819d243d604fc', //secret需自己提供，此处的secret我随机编写
  },
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hiddenLoading: true,
    //自己写
    pwd: '',
    user: '',
    eye: false,
    userInfo: {},
    wxicon: '../../images/wx.png'
  },

  switchEye: function switchEye(e) {
    this.setData({
      eye: !this.data.eye
    });
  },
  //监听用户名密码输入框
  bindPwd: function bindPwd(e) {
    var val = e.detail.value;
    this.setData({
      pwd: val
    });
  },

  bindUser: function bindUser(e) {
    var val = e.detail.value;
    this.setData({
      user: val
    });
  },

  //微信授权登录
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;
      var userInfo = {
        openid: wx.getStorageSync("user").openid,
        nickName: e.detail.userInfo.nickName,
        sex: e.detail.userInfo.gender,
        avatarUrl: e.detail.userInfo.avatarUrl,
        province: e.detail.userInfo.province,
        city: e.detail.userInfo.city
      };
      wx.request({
        url: 'https://www.fwj.jhlfs.top/welcome/wxLogin',
        data: userInfo,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function success(res) {
          wx.setStorageSync("USERSESSION", res.data.nickname);
          console.log(res.data)
          app.appData = {
            username: res.data.nickname,
            pic: res.data.avatarUrl,
            sex: res.data.sex,
          }
          wx.switchTab({
            url: '../home/home'
          })
        },
        fail: function() {
          self.setData({
            hiddenLoading: true
          });
          wx.showModal({
            title: '提示',
            content: '请求超时,请重新登录！',
            showCancel: false,
            confirmColor: "#1b65ce",
          })
        }
      })
      //授权成功后，跳转进入小程序首页
      // wx.switchTab({
      //   url: ''
      // })

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '提示',
        content: '您点击了取消，将无法进入小程序，请授权后再进入',
        showCancel: false,
        confirmText: '重新授权',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  },

  //点击登录
  login: function() {
    this.setData({
      hiddenLoading: false
    });
    var username = this.data.user;
    var userpwd = this.data.pwd;
    if (username == '' || userpwd == '') {
      this.setData({
        hiddenLoading: true
      });
      wx.showModal({
        title: '提示',
        content: '用户名或密码不能为空',
        showCancel: false,
        confirmColor: "#1b65ce",
      })
      return;
    }
    //发送请求验证
    var self = this;
    wx.request({
      url: 'https://www.fwj.jhlfs.top/',
      data: {
        username: username,
        userpwd: userpwd
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function success(res) {
        self.setData({
          hiddenLoading: true
        })
        var resData = res.data;
        if (resData.code == 0) {
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000
          })
          var nowtime = Date.parse(new Date());
          wx.setStorageSync("USERSESSION", username);
          wx.switchTab({
            url: '../home/home'
          })
          self.setData({
            pwd: ''
          });
        } else {
          wx.showModal({
            title: '提示',
            content: resData.msg,
            showCancel: false,
            confirmColor: "#1b65ce",
          })
        }
      },
      fail: function() {
        self.setData({
          hiddenLoading: true
        });
        wx.showModal({
          title: '提示',
          content: '请求超时,请重新登录！',
          showCancel: false,
          confirmColor: "#1b65ce",
        })
      },
    });

  },

  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function() {
    var that = this;
    //判断用户是否登录授权
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function(res) {
              //从数据库获取用户信息
              // that.queryUsreInfo();
              // //用户已经授权过
              // wx.switchTab({
              //   url: ''
              // })
            }
          });
        }
      }
    })
    //获取code，进一步获取openid
    wx.login({
      success: function(res) {
        console.log("res.code:" + res.code);
        if (res.code) {
          var d = that.globalData; //这里存储了appid、secret、token串  
          var url = 'https://api.weixin.qq.com/sns/jscode2session';
          wx.request({
            url: url,
            data: {
              appid: d.appid,
              secret: d.secret,
              grant_type: 'authorization_code',
              js_code: res.code
            },
            method: 'GET',
            success: function(res) {
              var obj = {};
              obj.openid = res.data.openid;
              console.log("openid:" + obj.openid);
              console.log("session_key:" + res.data.session_key);
              obj.expires_in = Date.now() + res.data.expires_in;
              wx.setStorageSync('user', obj); //存储openid 
            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    })

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //获取用户信息接口
  queryUsreInfo: function() {
    wx.request({
      url: getApp().globalData.urlPath + 'hstc_interface/queryByOpenid',
      data: {
        openid: getApp().globalData.openid
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log(res.data);
        getApp().globalData.userInfo = res.data;
      }
    })
  },
})